package com.augrain.microframework.trace.util;

import com.augrain.microframework.core.spring.SpringUtils;
import com.augrain.microframework.core.util.BeanUtils;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.trace.TraceConstant;
import com.augrain.microframework.trace.TraceProperty;
import com.augrain.microframework.trace.common.TraceLabel;
import org.slf4j.MDC;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * slf4j日志框架mdc工具
 *
 * @author biaoy
 * @since 2021/08/21
 */
public class MDCUtils {
    public static void put(TraceLabel traceLabel, TraceProperty traceProperty) {
        String pattern = traceProperty.getPattern();
        LinkedHashSet<String> patternSet = Arrays.stream(pattern.split(","))
                .map(String::trim)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toCollection(LinkedHashSet::new));

        Map<String, Object> traceMap = BeanUtils.bean2Map(traceLabel);
        String logLabel = fillLogLabel(patternSet, traceMap);
        MDC.put(TraceConstant.MDC_KEY, logLabel);
    }

    private static String fillLogLabel(LinkedHashSet<String> patternSet, Map<String, Object> traceMap) {
        Set<String> labelSet = new LinkedHashSet<>();

        for (String key : patternSet) {
            if (traceMap.containsKey(key)) {
                labelSet.add(key + ":" + traceMap.get(key));
            }
        }

        return String.join(",", labelSet);
    }

    public static void clear() {
        MDC.clear();
    }

    public static void continued(TraceLabel traceLabel) {
        TraceProperty property = SpringUtils.getBean(TraceProperty.class);
        put(traceLabel, property);
    }
}
